#include <iostream>
#include <thread>
#include <functional>
#include <mutex>
#include <chrono>

// 类A - 数据处理类
class DataProcessor {
private:
    std::function<void(const std::string&)> callback;
    std::thread workerThread;
    
public:
    // 设置回调函数
    void setCallback(std::function<void(const std::string&)> cb) {
        callback = cb;
    }
    
    // 启动工作线程
    void startProcessing() {
        workerThread = std::thread([this]() {
            // 模拟数据处理
            for (int i = 1; i <= 3; ++i) {
                std::this_thread::sleep_for(std::chrono::milliseconds(1000));
                
                // 处理完成后调用回调
                if (callback) {
                    std::string result = "Processing result " + std::to_string(i);
                    callback(result);  // 调用回调函数
                }
            }
        });
    }
    
    void waitForCompletion() {
        if (workerThread.joinable()) {
            workerThread.join();
        }
    }
};

// 类B - 主控制类
class MainController {
private:
    std::mutex printMutex;
    DataProcessor processor;
    
public:
    MainController() {
        // 设置回调函数
        processor.setCallback([this](const std::string& result) {
            // 这个回调在DataProcessor的线程中执行
            std::lock_guard<std::mutex> lock(printMutex);
            std::cout << "Callback received: " << result 
                      << " on thread: " << std::this_thread::get_id() << std::endl;
            std::cout << this << std::endl;
        });
    }
    
    void start() {
        std::cout << "MainController started on thread: " 
                  << std::this_thread::get_id() << std::endl;
        std::cout << this << std::endl;
        processor.startProcessing();
    }
    
    void waitForCompletion() {
        processor.waitForCompletion();
    }
};

int main() {
    MainController controller;
    controller.start();
    
    // 主线程继续做其他工作
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
    std::cout << "Main thread doing other work..." << std::endl;
    
    controller.waitForCompletion();
    return 0;
}